import uiautomator2 as u2
import os
import re
import random
import time


class Quark():
    def __init__(self, device_ip, device_port):
        os.system(f'adb connect {device_ip}:{device_port}')
        self.d = u2.connect(f'{device_ip}:{device_port}')
        self.d.implicitly_wait(10)
        self.width, self.height = self.d.window_size()
        self.task_app = ('com.quark.browser', '夸克')
        self.close_btn = self.d.xpath(
            f'//*[@resource-id="{self.task_app[0]}:id/noah_hc_close_button"]')
        self.close_icon = self.d.xpath(
            f'//*[@resource-id="{self.task_app[0]}:id/noah_close_icon"]')

        self.home_page = self.d.xpath(
            f'//*[@resource-id="{self.task_app[0]}:id/view_homepage"]')

        self.jiasu_pattern = r'^(我要直接拿奖励|立即前往加速|我要加速领奖|我要加速|去体验|拿奖励|我要直接领奖)$'
        self.device_info = f"""【设备信息】
型号：{self.d.device_info['brand']} {self.d.device_info['model']}
分辨率: {self.width}x{self.height}"""
        print(self.device_info)

    def get_all_texts(self):
        # 获取所有非空文本"
        els = self.d.xpath(
            '//*[@resource-id="android:id/content"]//*[@text]').all()
        return [
            el.text.strip() for el in els
            if el.text.strip()
        ]

    def is_contain_all_text(self, texts, all_texts):
        # 是否包含了所有的文本
        return all(text in all_texts for text in texts)

    def is_match_text(self, pattern, texts):
        # 正则是否匹配到文本
        return any(re.search(pattern, text) for text in texts)

    def swipe_down(self):
        # 向下随机滑动
        start_x = random.randint(self.width // 4,
                                 self.width * 3 // 4)  # 水平方向随机位置
        start_y = random.randint(self.height // 2,
                                 self.height * 3 // 4)  # 从屏幕下半部分开始
        end_x = start_x + random.randint(-50, 50)  # 水平方向轻微变化
        end_y = start_y - \
            random.randint(self.height // 4, self.height // 3)

        # 随机滑动持续时间
        duration = random.uniform(0.2, 0.5)

        # 执行滑动
        self.d.swipe(start_x, start_y, end_x, end_y, duration)

    def click_text(self, text):
        # 点击文本
        try:
            print(f"点击: {text}")
            self.d.xpath(f'//*[@text="{text}"]').click()
        except:
            print(f"点击: {text} 出现异常！")
            pass

    def click_contain_text(self, text):
        # 点击包含指定内容的文本
        try:

            el = self.d.xpath(f'//*[contains(@text,"{text}")]')
            print(f"点击: {el.get_text()}")
            el.click()
        except:
            print(f"点击: {text} 出现异常！")
            pass

    def click_match_text(self, pattern, texts):
        # 点击正则匹配到的第1个文本
        text = [str for str in texts if re.search(pattern, str)][0]
        self.click_text(text)

    def is_task_app(self):
        # 判断是否为任务APP
        return self.d.app_current().get("package") == self.task_app[0]

    def switch_task_app(self):
        # 切换至任务APP
        if not self.is_task_app():
            print('切换至任务APP...')
            time.sleep(1)
            self.d.press("recent")
            time.sleep(1)
            if self.task_app[1] in self.get_all_texts():
                self.click_text(self.task_app[1])

    def jump_task(self, wait_time):
        # 执行APP跳转类任务
        time.sleep(3)
        if self.is_task_app() or self.d.app_current().get("package") == "com.miui.securitycenter":
            if "奖励已领取" in self.get_all_texts():
                pass
            else:
                self.d.press('home')
                time.sleep(wait_time)
                self.switch_task_app()
                self.d.press('back')
        else:
            time.sleep(wait_time)
            self.d.app_stop(self.d.app_current().get("package"))
            self.switch_task_app()
            self.d.press('back')

    def load_task_text(self):
        counter = 0
        while True:
            texts = self.get_all_texts()
            if len(texts) > 0:
                print("当前文本:", texts)
                return texts
            elif counter > 10:
                print(f'加载任务文本失败，重启{self.task_app[1]}！')
                self.d.app_stop(self.d.app_current().get("package"))
                return []
            time.sleep(1)
            counter += 1

    def start_task(self):
        # 开始任务，点击任务
        self.d.screen_on()
        texts = self.get_all_texts()

        if self.is_match_text(r'video_again|get_pull|看视频再领\d+金币', texts):
            self.click_match_text(r'video_again|get_pull|看视频再领\d+金币', texts)

        task_list = self.d.xpath(
            "//*[@text='去完成']/parent::*/android.widget.TextView[1]").all()
        task_texts = []
        for task in task_list:
            if re.match(r'^(看视频领|浏览广告得)金币$', task.text):
                task_texts.append(task.text)

        if len(task_texts) != 0:
            self.click_text(task_texts[0])
        self.execute_task()

    def execute_task(self):
        while True:
            texts = self.load_task_text()
            if self.close_btn.exists:
                if '奖励已发放' in texts:
                    self.close_btn.click()
                    break

                elif self.is_match_text(r'.*-阿里巴巴$|点击商品，领取奖励', texts):
                    self.swipe_down()
                    # self.d(textMatches=r'点击商品，领取奖励|¥').click(timeout=3.0)
                    self.click_match_text(r'点击商品，领取奖励|¥', self.get_all_texts())
                    if self.d(text='奖励已发放').wait(timeout=3.0):
                        self.close_btn.click()
                    break
                elif self.d(textMatches=r'^(奖励将于\d+秒后发放|再看\d+秒可获得\d+肥料)$').exists():
                    if self.d(text="奖励已发放").wait(timeout=50.0):
                        self.close_btn.click()
                    break
                elif "立即点击领取" in texts:
                    self.click_text('立即点击领取')
                    self.jump_task(15)
                    break
                elif len(texts) == 1 or self.is_contain_all_text({'广告', 'UC芭芭农场'}, texts):
                    break

                elif "立即点击下载" in texts or self.d(textMatches=r'领取|获得|奖励').wait(timeout=3.0):
                    self.close_btn.click()
                    break

            elif self.is_match_text(r'穿山甲|可直接拿奖励', texts):
                if self.is_match_text(r'^(奖励已领取|已领取|已领取奖励|打开应用或观看0s领取奖励|0s)$', texts):
                    self.click_contain_text('跳过')
                    break

                elif texts.count('去体验') >= 2:
                    print('点击: 去体验')
                    self.d.xpath('//*[@text="去体验"]').all()[-1].click()
                    self.jump_task(10)
                    break

                elif "继续观看" in texts:
                    self.click_text('继续观看')
                    break

                elif self.is_match_text(self.jiasu_pattern, texts):
                    self.click_match_text(
                        self.jiasu_pattern, texts)
                    self.jump_task(17)
                    break

                elif self.is_match_text(r'^去体验\d+秒可立即领奖$', texts) and not self.is_match_text(self.jiasu_pattern, texts):
                    self.d.click(self.width*0.5, self.height*0.6)
                    self.jump_task(16)
                    break

                elif self.is_match_text(r'^(再体验\d+秒可立即领奖|\d+s)$', texts):
                    if "返回继续体验" in texts:
                        self.click_text('返回继续体验')
                        break
                    elif "再试一次" in texts:
                        self.click_text('再试一次')
                        self.jump_task(16)
                        break
                    elif "请勿中断浏览以免任务失败" in texts and not self.is_match_text(r'^(再试一次)$', texts):
                        self.d.click(self.width*0.5, self.height*0.52)
                        self.jump_task(16)
                        break
                    else:
                        # self.click_contain_text('跳过')
                        break
                elif "返回继续体验" in texts and not self.is_match_text(r'^(奖励已领取|再体验\d+秒可立即领奖)$|跳过', texts):
                    self.d.click(self.width*0.2, self.height*0.06)
                    if "福利中心" not in self.get_all_texts():
                        print('任务结束异常！')
                        self.switch_task_app()
                        close_bounds = (self.width*0.93, self.height*0.06)
                        print("点击坐标：", close_bounds)
                        self.d.click(*close_bounds)
                    break
                elif len(texts) == 1 and texts[0] == '穿山甲':
                    self.d.app_stop(self.d.app_current().get("package"))
                    break

            elif "百度网盟推广" in texts and "关闭" not in texts:
                self.d.xpath(
                    '//*[@text="百度网盟推广"]/../../following-sibling::android.widget.ImageView[1]'
                ).click()
                break
            elif "放弃福利" in texts:
                try:
                    self.d.click(*self.d(text='放弃福利').center())
                    break
                except:
                    print('点击放弃福利异常！')
                    break
                
            elif self.is_match_text(r'继续看(广告|视频)', texts):
                self.click_contain_text('继续看')
                break

            elif "秒后发放" in texts:
                break

            elif "长按加速视频 获取奖励" in texts and self.is_match_text(r'^\d+$', texts):
                self.d(text='长按加速视频 获取奖励').long_click(duration=5.0)
                break

            elif "立即获取" in texts and not self.is_match_text(r'^\d{1,2}$', texts):
                self.click_contain_text('跳过')
                break

            elif self.is_match_text(r'^(奖励已领取|已领取|已领取奖励|打开应用或观看0s领取奖励|0s)$', texts) and "跳过" not in texts:
                close_bounds = (self.width*0.93, self.height*0.06)
                print("点击坐标：", close_bounds)
                self.d.click(*close_bounds)
                if "福利中心" not in self.get_all_texts():
                    print('任务结束异常！')
                    self.switch_task_app()
                    close_bounds = (self.width*0.93, self.height*0.03)
                    print("点击坐标：", close_bounds)
                    self.d.click(*close_bounds)
                break

            elif self.is_contain_all_text({'已领取奖励', '跳过'}, texts):
                self.click_text('跳过')
                break

            # elif texts.count('美团超值福利') >= 2 or texts.count('高德地图') >= 2 or texts.count('飞猪旅行app') >= 2 or texts.count('苏宁热卖，精选爆款') >= 2:
            #     self.d.press('back')
            #     break

            elif self.is_match_text(r'^(进入微信小游戏立即玩|去微信看短剧)$', texts):
                self.click_match_text(r'^(进入微信小游戏立即玩|去微信看短剧)$', texts)
                self.jump_task(15)
                break

            elif self.is_match_text(r'^(去微信看全集|进入微信小游戏自由畅玩)$', texts):
                self.d.xpath(
                    '//*[@text="进入微信小游戏自由畅玩" or @text="去微信看全集"]/../../../preceding-sibling::android.widget.FrameLayout/android.widget.ImageView'
                ).all()[-1].click()
                break

            elif self.is_contain_all_text({'淘宝精选', '浏览'}, texts):
                while True:
                    texts = self.get_all_texts()
                    if "已领取" in texts:
                        self.click_text('已领取')
                        break
                    self.swipe_down()
                    time.sleep(3)

            elif self.is_match_text(r'^应用名称.*功能介绍$', texts) and "任务资源加载中..." not in texts:
                self.d.press('back')
                break

            elif "我要免看本次广告" in texts:
                self.d.xpath(
                    '//*[@text="恭喜获得特权"]/../preceding-sibling::android.view.ViewGroup//android.widget.ImageView'
                ).click()
                break

            elif self.is_contain_all_text({'已完成任务', '恭喜', '获得奖励'}, texts):
                self.d.press('back')
                break

            # elif "拼好饭万家品牌百万亮厨上线" in texts and not self.is_match_text(r'跳过|获取|应用名称', texts):
            #     self.d.press('back')
            #     break

            elif self.is_match_text(r'^(免费获取|恭喜获得奖励！|是否下载应用 ？|app的用户隐私协议|去桌面访问|format,webp|swt_rightdh|网页无法打开)$', texts) or self.is_contain_all_text(
                    {"应用详情", "立即下载"}, texts):
                self.d.press('back')
                break

            elif "反馈" in texts and not self.is_match_text(r'跳过|去领|已领取', texts):
                if "点击取消静音" in texts:
                    time.sleep(8)
                    self.d.click(self.width*0.91, self.height*0.95)
                    break
                elif self.is_match_text(r'^(发送验证码|侵权投诉|请输入)$', texts):
                    self.d.press('back')
                    break
                else:
                    try:
                        self.d.xpath(
                            '//*[@text="反馈"]/../following-sibling::android.widget.LinearLayout//android.widget.ImageView'
                        ).click()
                        break
                    except:
                        print('任务关闭异常！')
                        close_bounds = (self.width*0.92, self.height*0.04)
                        print("尝试点击坐标：", close_bounds)
                        self.d.click(*close_bounds)
                        break

            elif self.is_match_text(r'^(加速领奖入口|点此处下载)$', texts):
                while True:
                    time.sleep(8)
                    self.d.press('back')
                    time.sleep(1)
                    if not "继续观看" in self.get_all_texts():
                        break
                    self.click_text('继续观看')

            elif self.is_match_text(r'再逛\d+秒后可领奖', texts):
                self.swipe_down()
                break

            elif '点击' in texts and self.is_match_text('^(下载或打开第三方应用)$', texts):
                close_bounds = (self.width*0.91, self.height*0.07)
                print("点击坐标：", close_bounds)
                self.d.click(*close_bounds)
                break

            elif self.is_contain_all_text(['svg%3e', '搜索'], texts):
                if self.is_match_text(r"^(\d+秒|\d{2}:\d{2})$", texts) and "00:00" not in texts:
                    self.swipe_down()
                    break
                else:
                    self.click_text(r'svg%3e')
                    break

            elif "svg%3e" in texts and not self.is_match_text(r'秒后可领奖', texts):
                self.click_text('svg%3e')
                break

            elif self.is_match_text(r'打开App体验\d+秒，即可获得奖励', texts) and not self.is_match_text(r'^(打开第三方应用|关闭广告)$', texts):
                close_bounds = (self.width*0.92, self.height*0.04)
                print("点击坐标：", close_bounds)
                self.d.click(*close_bounds)
                break

            elif self.is_contain_all_text({'打开第三方应用', '关闭广告'}, texts):
                self.click_text('打开第三方应用')
                self.jump_task(15)
                break

            elif "点击广告，即可获得奖励" in texts:
                self.click_match_text(r'^(点击广告拿奖励|点击打开或下载第三方应用)$', texts)
                break

            elif self.is_match_text(r'^(恭喜获得奖励|应.*备案信息)$', texts) and not self.is_match_text(r'跳过|秒后', texts):
                close_bounds = (self.width*0.91, self.height*0.07)
                print("点击坐标：", close_bounds)
                self.d.click(*close_bounds)
                if "福利中心" not in self.get_all_texts():
                    print('任务结束异常！')
                    self.switch_task_app()
                    close_bounds = (self.width*0.91, self.height*0.04)
                    print("尝试点击坐标：", close_bounds)
                    self.d.click(*close_bounds)
                break

            # elif self.d.xpath('//*[@resource-id="com.UCMobile.adn_meishu_sdk:id/ms_reward_close_button"]').exists and not self.d.xpath('//*[@resource-id="com.UCMobile.adn_meishu_sdk:id/ms_process_bar"]').exists:
            #     self.d.xpath(
            #         '//*[@resource-id="com.UCMobile.adn_meishu_sdk:id/ms_reward_close_button"]').click()
            #     break

            elif self.close_icon.exists:
                self.close_icon.click()
                break

            elif self.is_contain_all_text({'福利中心', '去完成'}, texts):
                break

            elif self.home_page.exists and "福利中心" in texts:
                self.click_text('福利中心')
                break

            elif self.is_match_text(r'^(残忍离开|坚持退出|关闭广告|退出广告|抓住奖励机会)$', texts):
                self.click_match_text(r'^(残忍离开|坚持退出|关闭广告|退出广告|抓住奖励机会)$', texts)
                break

            elif not self.is_task_app():
                time.sleep(2)
                if self.is_contain_all_text({'淘宝精选', '浏览得奖励'}, texts):
                    break
                else:
                    self.switch_task_app()
                    break

            elif self.is_contain_all_text({'秒后即可获得奖励', '浏览页面'}, texts):
                break
            else:
                self.d.press('back')
                break
            time.sleep(1)

    def run_task(self):
        # 运行程序
        while True:
            texts = self.get_all_texts()
            if self.is_contain_all_text({'福利中心', '去完成'}, texts) and not self.is_match_text(r'^(看视频领|浏览广告得)金币$', texts):
                print('任务完成，程序结束！')
                break
            self.start_task()
            time.sleep(1)


if __name__ == '__main__':
    device_ip = input('请输入设备IP[127.0.0.1]:') or "127.0.0.1"
    device_port = input('请输入设备端口[5555]:') or "5555"
    quark = Quark(device_ip, device_port)
    quark.run_task()
